package tablet.module_user.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.lib.app.ARouterPathUtils;
import com.lib.app.CodeUtil;
import com.lib.bean.ToLiveBean;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.db.shared_prefrences.interfaces.UserCacheInterface;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.clear_cache.ClearDataUtils;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.views.circle_image.niv.NiceImageView;
import com.lib.fastkit.views.dialog.http.DialogUtils;
import com.lib.fastkit.views.dialog.normal.CoachAIStudyDialog;
import com.lib.fastkit.views.dialog.zenhui.AlertDialog;
import com.lib.fastkit.views.load_state_view.MultiStateView;
import com.lib.fastkit.views.recyclerview.tool.MyLinearLayoutManager;
import com.lib.fastkit.views.recyclerview.zhanghongyang.base.ViewHolder;
import com.lib.fastkit.views.spring_refresh.container.DefaultFooter;
import com.lib.fastkit.views.spring_refresh.container.DefaultHeader;
import com.lib.fastkit.views.spring_refresh.widget.SpringView;
import com.lib.http.call_back.HttpDialogCallBack;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.observer.ObserverManager;
import com.lib.ui.adapter.BaseAdapter;
import com.lib.ui.fragment.BaseAppFragment;
import com.lib.utls.glide.GlideConfig;

import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.OnClick;
import tablet.module_user.R;
import tablet.module_user.R2;
import tablet.module_user.activity.SetActivity;
import tablet.module_user.bean.LoginOutBean;
import tablet.module_user.bean.StudentWorkRecordBean;
import tablet.module_user.bean.StudnetConnectaBean;
import tablet.module_user.bean.UserInfoBean;
import tablet.module_user.fragment.studentcollect.StudentFamousResFragment;
import tablet.module_user.fragment.studentcollect.StudentRecordVideoFragment;
import tablet.module_user.fragment.studentcollect.StudentStudyResFragment;

public class StudentInfoRecordFragment extends BaseAppFragment {

    @BindView(R2.id.iv_user)
    NiceImageView ivUser;
    @BindView(R2.id.lin_name)
    LinearLayout linName;
    @BindView(R2.id.tv_name)
    TextView tvName;
    @BindView(R2.id.tv_school)
    TextView tvSchool;
    @BindView(R2.id.tv_num)
    TextView tvNum;
    @BindView(R2.id.lin_ainum)
    LinearLayout linAinum;
    @BindView(R2.id.tv_zan)
    TextView tvZan;
    @BindView(R2.id.tv_flower)
    TextView tvFlower;
    @BindView(R2.id.lin_zanflower)
    LinearLayout linZanflower;

    @BindView(R2.id.lin_class)
    LinearLayout linClass;
    @BindView(R2.id.lin_ask)
    LinearLayout linAsk;
    @BindView(R2.id.lin_order)
    LinearLayout linOrder;
    @BindView(R2.id.lin_message)
    LinearLayout linMessage;
    @BindView(R2.id.lin_setting)
    LinearLayout linSetting;
    @BindView(R2.id.lin_shop)
    LinearLayout linShop;
    @BindView(R2.id.lin_exit)
    LinearLayout linExit;

    @BindView(R2.id.springView)
    SpringView springView;
    @BindView(R2.id.state_view)
    MultiStateView stateView;
    @BindView(R2.id.rv_record)
    RecyclerView rvRecord;

    @BindView(R2.id.tl_tabs)
    TabLayout tlTabs;
    @BindView(R2.id.vp_content)
    ViewPager vpContent;

    UserInfoBean.ObjBean userInfoBean;

    List<Fragment> fgList;
    public String[] titleArr = {"录播课程", "教辅资料", "名师资源"};

    StudentRecordVideoFragment videoFragment;//录播课程
    StudentStudyResFragment resFragment;//教辅资料
    StudentFamousResFragment famousResFragment;//名师资源

    int page = 0;
    StudentWorkRecordAdapter recordAdapter;
    List<StudentWorkRecordBean.ObjBean.JobRecordBean.RowsBean> recordList = new ArrayList<>();

    //用户记录作业历史详情的头部地址
    public String recordWorkHeadUrl = "";

    StudentInfoRecordFragment infoRecordFragment;

    StudnetConnectaBean.ObjBean connectaBean;

    private DialogUtils dialogUtils;

    @Override
    protected void onCreateView(View view, Bundle savedInstanceState) {

        infoRecordFragment = this;

        //初始化基础控件和作业记录
        initBaseViews();

        dialogUtils = new DialogUtils();

        //获取用户信息
        getUserInfo();

        //初始化作业记录数据
        initUserWorkRecordData();

        //加载右边滑动区域
        initViewPager();
        initTabNormal();

    }

    @Override
    public void onResume() {
        super.onResume();

        if (infoRecordFragment.getUserVisibleHint()) {

            LogUtil.e("infoRecordFragment状态为可见！");

            //初始化基础控件和作业记录
            initBaseViews();

            //获取用户信息
            getUserInfo();

            //初始化作业记录数据
            initUserWorkRecordData();

            //加载右边滑动区域
            initViewPager();
            initTabNormal();

        }

    }

    private void initBaseViews() {

        stateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
        stateView.setMultiStateViewLisener(new MultiStateView.MultiStateViewLisener() {
            @Override
            public void onTryAgain() {

                //初始化作业记录数据
                initUserWorkRecordData();
            }
        });

        springView.setHeader(new DefaultHeader(getActivity()));
        springView.setFooter(new DefaultFooter(getActivity()));

        springView.setListener(new SpringView.OnFreshListener() {
            @Override
            public void onRefresh() {
                page = 0;

                initUserWorkRecordData();
                springView.onFinishFreshAndLoad();

            }

            @Override
            public void onLoadmore() {

                ++page;
                initUserWorkRecordData();
                springView.onFinishFreshAndLoad();
            }
        });

        recordAdapter = new StudentWorkRecordAdapter(getActivity(), recordList);
        MyLinearLayoutManager manager = new MyLinearLayoutManager(getActivity());
        rvRecord.setLayoutManager(manager);
        rvRecord.setAdapter(recordAdapter);

    }

    private void getUserInfo() {

        HttpUtils.with(getActivity())
                .addParam("requestType", "UNIFIED_INTERFACE")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<UserInfoBean>() {
                    @Override
                    public void onSuccess(UserInfoBean result) {

                        if (result.getCode() == CodeUtil.CODE_200) {
                            if (result.getObj() != null) {

                                userInfoBean = result.getObj();

                                initUserView();

                                //设置剩余AI辅导次数
                                if (result.getObj().getSurplus_classes() > -1) {
                                    tvNum.setText(result.getObj().getSurplus_classes() + "次");
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }

    private void initUserView() {

        if (userInfoBean != null) {

            UserInfoBean.ObjBean.PersonalInfoBean personalInfoBean = userInfoBean.getPersonal_info();
            if (StringUtil.isNotEmpty(personalInfoBean.getPhoto_url(), true)) {
                Glide.with(getActivity())
                        .load(personalInfoBean.getPhoto_url())
                        .apply(GlideConfig.getCircleOptions())
                        .into(ivUser);
            }

            if (StringUtil.isNotEmpty(personalInfoBean.getName(), true)) {
                tvName.setText(personalInfoBean.getName());
            }

            if (StringUtil.isNotEmpty(personalInfoBean.getTotal() + "", true)) {
                tvSchool.setText(personalInfoBean.getTotal() + "");
            }

            //点赞和鲜花数量
            if (personalInfoBean.getLike_total() > -1) {
                tvZan.setText(personalInfoBean.getLike_total() + "");
            }
            if (personalInfoBean.getRed_flower() > -1) {
                tvFlower.setText(personalInfoBean.getRed_flower() + "");
            }

        }

    }


    private void initUserWorkRecordData() {

        HttpUtils.with(getActivity())
                .addParam("requestType", "JOB_RECORD")
                .addParam("page", page)
                .addParam("limit", 10)
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<StudentWorkRecordBean>() {
                    @Override
                    public void onSuccess(StudentWorkRecordBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            if (StringUtil.isNotEmpty(result.getObj().getJob_record_url(), true)) {
                                recordWorkHeadUrl = result.getObj().getJob_record_url();
                            }

                            if (result.getObj().getJob_record().getRows().size() > 0) {

                                if (page == 0 && recordList.size() > 0) {
                                    recordList.clear();
                                }

                                recordList.addAll(result.getObj().getJob_record().getRows());
                                recordAdapter.notifyDataSetChanged();

                            }

                            stateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {

                            stateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        }
                    }

                    @Override
                    public void onError(String e) {

                        if (stateView != null) {
                            stateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        }
                    }
                });


    }


    @OnClick({R2.id.lin_name, R2.id.lin_shop, R2.id.lin_class, R2.id.lin_ask,
            R2.id.lin_order, R2.id.lin_message, R2.id.lin_setting,R2.id.lin_exit})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.lin_name) {

            showNick();
        } else if (i == R.id.lin_shop) {

//            String url = "http://192.168.0.100:8848/flat.html#/mall";

//            String url = "http://192.168.0.10:81/xst_web/flat.html#/mall";

            String url = "https://h5.xuesituedu.com/xst_web/flat.html#/mall";
            ARouter.getInstance().build(ARouterPathUtils.Tablet_App_NormalDetailWebActivity)
                    .withString("urlPath", url).navigation();

        } else if (i == R.id.lin_class) {

            showToast("该功能正在建设中，敬请期待");
        } else if (i == R.id.lin_ask) {

            ARouter.getInstance().build(ARouterPathUtils.Dayi_AskQuestionActivity).navigation();
        } else if (i == R.id.lin_order) {

            ARouter.getInstance().build(ARouterPathUtils.Tablet_User_OrderListActivity).navigation();

        } else if (i == R.id.lin_message) {

            ARouter.getInstance().build(ARouterPathUtils.User_MessageActivity).navigation();

        } else if (i == R.id.lin_setting) {

            ARouter.getInstance().build(ARouterPathUtils.User_SetActivity).navigation();
        }else if (i == R.id.lin_exit) {//退出------清理数据

            clearTabletCache();
        }
    }


    private void clearTabletCache() {

        CoachAIStudyDialog.getInstance()
                .setTitle("清理缓存")
                .setContent("你确认要缓存么?")
                .setCancelListener(new CoachAIStudyDialog.CancelListener() {
                    @Override
                    public void onCancel() {

                    }
                })
                .setSureListener(new CoachAIStudyDialog.SurelListener() {

                    @Override
                    public void onSure() {
                        dialogUtils.showNormalDialog(getActivity(), "缓存清理中...");

                        ClearDataUtils.clearAllCache(getActivity());
                        ClearDataUtils.cleanWebViewCache(getActivity());

                        /**
                         * 清除 token
                         */
//                        SharedPreferenceManager.getInstance(SetActivity.this).getUserCache().setUserToken("");

                        /**
                         * 清除等待状态
                         */
                        SharedPreferenceManager.getInstance(getActivity()).getUserCache().setIsWait(0);

                        /**
                         * 清除图片缓存
                         * 该方法必须在主线程
                         */
                        Glide.get(getActivity()).clearMemory();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {

                                /**
                                 * 清除图片缓存
                                 * 该方法必须在子线程
                                 */
                                Glide.get(getActivity()).clearDiskCache();

                            }
                        }).start();

                        dialogUtils.dismiss();

                        //清理缓存之后，需要重新登录
//                        ARouter.getInstance().build(ARouterPathUtils.User_LoginActivity).navigation();

                    }


                })
                .show(getChildFragmentManager());

    }

    NickNameFragment nickNameFragment;

    private void showNick() {

        final AlertDialog dialog = new AlertDialog.Builder(getActivity())
                .setContentView(R.layout.dialog_nick)
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (nickNameFragment != null) {
                            getActivity().getSupportFragmentManager().beginTransaction().remove(nickNameFragment).commit();
                            nickNameFragment = null;
                        }
                    }
                }).fullWidth()
                .addDefaultAnimation()
                .show();

        nickNameFragment = (NickNameFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment_nick);

        nickNameFragment.setOnNomalChangeListener(new NickNameFragment.NormalChangeListener() {
            @Override
            public void onNomalChange(String str) {

                if (StringUtil.isNotEmpty(str, true)) {

                    dialog.dismiss();

                    //将修改的昵称发送到服务器
                    sendChangeNameToService(str);

                } else {
                    showToast("请输入您想要修改的昵称！");
                }
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_student_inforecord;
    }


    private void sendChangeNameToService(final String str) {

        HttpUtils.with(getActivity())
                .addParam("requestType", "CHANGE_NAME")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .addParam("name", str)
                .execute(new HttpDialogCallBack<LoginOutBean>() {
                    @Override
                    public void onSuccess(LoginOutBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {

                            showToast("昵称修改成功！");
                            tvName.setText(str);
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }


    class StudentWorkRecordAdapter extends BaseAdapter<StudentWorkRecordBean.ObjBean.JobRecordBean.RowsBean> {


        public StudentWorkRecordAdapter(Context context, List<StudentWorkRecordBean.ObjBean.JobRecordBean.RowsBean> mData) {
            super(context, mData);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_workrecord;
        }

        @Override
        protected void toBindViewHolder(ViewHolder holder, int position, List<StudentWorkRecordBean.ObjBean.JobRecordBean.RowsBean> mData) {

            final StudentWorkRecordBean.ObjBean.JobRecordBean.RowsBean rowsBean = mData.get(position);

            if (StringUtil.isNotEmpty(rowsBean.getTeacher_name(), true)) {
                holder.setText(R.id.tv_name, rowsBean.getTeacher_name());
            }

            if (StringUtil.isNotEmpty(rowsBean.getCreation_date(), true)) {
                holder.setText(R.id.tv_date, rowsBean.getCreation_date());
            }

            TextView tvDetail = holder.getView(R.id.tv_detail);
            LinearLayout linItem = holder.getView(R.id.lin_item);
//            tvDetail.setVisibility(View.GONE);
            linItem.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (StringUtil.isNotEmpty(recordWorkHeadUrl, true)) {
                        String recordUrl = recordWorkHeadUrl +
                                SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserPhone() +
                                "/" + rowsBean.getCreation_date();

                        ARouter.getInstance().build(ARouterPathUtils.Tablet_App_NormalDetailWebActivity)
                                .withString("urlPath", recordUrl).navigation();
                    }
                }
            });
        }
    }


    /**
     * 初始化ViewPager，方便后期与tabLayout关联
     */
    private void initViewPager() {
        if (fgList == null)
            fgList = new ArrayList<>();

        videoFragment = new StudentRecordVideoFragment();
        resFragment = new StudentStudyResFragment();
        famousResFragment = new StudentFamousResFragment();

        addFragmentToList();

        ViewPagerAdapter pagerAdapter = new ViewPagerAdapter(getChildFragmentManager(), fgList);
        vpContent.setAdapter(pagerAdapter);
        pagerAdapter.notifyDataSetChanged();

    }

    public void addFragmentToList() {

        if (fgList.size() > 0)
            fgList.clear();

        fgList.add(videoFragment);
        fgList.add(resFragment);
        fgList.add(famousResFragment);
    }

    /**
     * 初始化顶部标签
     */
    private void initTabNormal() {
        tlTabs.setupWithViewPager(vpContent);

        tlTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //添加选中Tab的逻辑
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                //添加未选中Tab的逻辑
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                //再次选中tab的逻辑
            }
        });

    }


    /**
     * ViewPager的适配器。
     */
    class ViewPagerAdapter extends FragmentPagerAdapter {

        List<Fragment> fragmentList;

        public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) {
            super(fm);
            this.fragmentList = fragmentList;
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titleArr[position];
        }
    }

    private void goToClass(final StudnetConnectaBean.ObjBean connectaBean) {

        //保存课程的类型以及该课程的Id，用于RoomControlFragment分享
        final UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(getActivity()).getUserCache();
        userCacheInterface.setBussessType(connectaBean.getType() + "");
        userCacheInterface.setCourseId(connectaBean.getId() + "");

        HttpUtils.with(getActivity())
                .addParam("requestType", "TO_CLASS")
                .addParam("course_type", connectaBean.getType())
                .addParam("course_id", connectaBean.getId())
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .execute(new HttpDialogCallBack<ToLiveBean>() {
                    @Override
                    public void onSuccess(ToLiveBean result) {

                        if (result.getCode() == CodeUtil.CODE_200) {

                            String roomToken = result.getObj().getRoomtoken();
                            String teacherPhone = result.getObj().getPhoen();

                            LogUtil.e("teacherPhone=" + teacherPhone +
                                    "roomName=" + result.getObj().getRoomname() + "uuid=" + result.getObj().getUuid()
                                    + "roomToken的值为：" + roomToken);

                            ARouter.getInstance().build(ARouterPathUtils.Tablet_CoachStudyLivingActivity)
                                    .withString("roomToken", roomToken)
                                    .withString("teacherPhone", teacherPhone)
                                    .withString("roomName", result.getObj().getRoomname())
                                    .withString("userPhone", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserPhone())
                                    .withString("uuid", result.getObj().getUuid())
                                    .withString("whitetoken", result.getObj().getWhitetoken())
                                    .withString("course_id", connectaBean.getId() + "")
                                    .navigation();

                            //将是否等待数据设置为0，方便外部判断
                            UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(getActivity()).getUserCache();
                            userCacheInterface.setIsWait(0);

                            ObserverManager.getInstance().notifyObserver("CloseWaitActivity");
                        }

                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }

}
